package com.woniuxy.amusementparkos.service.fzw.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.woniuxy.amusementparkos.dao.fzw.OrganizationDao;
import com.woniuxy.amusementparkos.entity.fzw.Organization;
import com.woniuxy.amusementparkos.entity.fzw.Role;
import com.woniuxy.amusementparkos.exception.fzw.OrganizationInUseException;
import com.woniuxy.amusementparkos.exception.fzw.RoleInUseException;
import com.woniuxy.amusementparkos.service.fzw.OrganizationService;
@Service
public class OrganizationServiceImp implements OrganizationService{
	@Autowired
	OrganizationDao organizationDao;
	

	@Override
	public Organization selectOrganizationNameById(int organization_id) {
		return organizationDao.selectOrganizationNameById(organization_id);
	}


	@Override
	public List<Organization> selectAllOrganizationNames() {
		return organizationDao.selectAllOrganizationNames();
	}


	@Override
	public List<Organization> selectAllOrganizationByPageNumber(Integer page, Integer limit) {
		return organizationDao.selectAllOrganizationByPageNumber((page-1)*10,limit);
	}

	/***
	 * 添加组织信息
	 */
	@Override
	public void insertOrganization(Organization organization) {
		organizationDao.insertOrganization(organization);
	}


	/**
	 * 查询组织是否正被用户使用
	 */
	@Override
	public void selectOrganizationByOrganizationIds(int[] organization_ids) {
		//默认为-1，若查到用户，则根据-1判断
		int user_id=-1;
		//创建一个集合用来存放用户正在使用的角色id
		List<Integer> usingOrganization = new ArrayList<Integer>();
		for(Integer organization_id:organization_ids) {
		user_id=-1;//重新赋值
		user_id=organizationDao.selectUserByOrganization_id(organization_id);
		//如果查询到用户不为空，则说明该角色正在被使用，则存放在数组里
		if(user_id!=-1) {
			usingOrganization.add(organization_id);
		}
	}
		//最后判断数组里是否存放有已被用户使用的组织，有则抛异常，无法删除
		if(!usingOrganization.isEmpty()) {
			//将正在使用的角色名查询出来
			String[] organizationNames=organizationDao.selectOrganizationsByIds(usingOrganization);
			String names="";
			for(String name:organizationNames) {
				names+=name+"、";
			}
			names=names.substring(0,names.length()-1);
			System.out.println(names);
			throw new OrganizationInUseException("组织：  "+names+"      正在使用中，无法删除！");
		}
	}

	/**
	 * 删除组织信息
	 */
	@Override
	public void deleteOrganizations(int[] organization_ids) {
		organizationDao.deleteOrganizations(organization_ids);
	}

	/**
	 * 编辑保存组织信息
	 */
	@Override
	public void updateOrganization(Organization organization) {
		organizationDao.updateOrganization(organization);
	}
	@Override
	public Long selectCount() {
		return organizationDao.selectCount();
	}	
	
}
